package com.ruoyi.modules.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.modules.domain.dto.VideoDataDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;


@Slf4j
public class DouyinRequestUtil {
    public static final String client_key = "awir56cotsu9ylua";
    private static final String client_secret = "cc91386677baa23197dbb0139c5efe84";


    private static RestTemplate restTemplate;
    static {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        //客户端与服务端建立连接超时时间
        factory.setConnectTimeout(1000);
        //客户端从服务端读取数据的超时时间
        factory.setReadTimeout(2000);
        restTemplate = new RestTemplate(factory);
    }


    /**
     *  登录根据code
     * @param code
     * @return
     */
    public static JSONObject loginByCode(String code) {

        String requestUrl = "https://open.douyin.com/oauth/access_token/";
        //请求参数
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("client_key", client_key);
        params.add("client_secret", client_secret);
        params.add("grant_type", "authorization_code");
        params.add("code", code);


        log.info("请求地址 ： {}  请求参数 ： {}", requestUrl, params);

        //请求头
        HttpHeaders headers = new HttpHeaders();

        //heads信息和body信息组装
        HttpEntity<Object> httpEntity = new HttpEntity<>(params, headers);

        ResponseEntity<String> responseEntity = restTemplate.postForEntity(requestUrl, httpEntity, String.class);
        return  getResult(responseEntity.getBody(), "登录授权");
    }


    /**
     *  获取用户信息
     * @return
     */
    public static JSONObject getUserInfo(String open_id, String access_token) {

        String requestUrl = "https://open.douyin.com/oauth/userinfo/" +
                "?open_id=" + open_id +
                "&access_token=" + access_token;

        log.info("请求地址 ： {}  ", requestUrl);

        ResponseEntity<String> responseEntity = restTemplate.getForEntity(requestUrl, String.class);
        JSONObject jsonObject = getResult(responseEntity.getBody(), "获取用户信息");


        //手机号解密
        String encrypt_mobile = jsonObject.getString("encrypt_mobile");
        if (StringUtils.isNotEmpty(encrypt_mobile)) {
            byte[] clientSecretBytes = client_secret.getBytes();
            SecretKey secretKey = new SecretKeySpec(clientSecretBytes, 0, clientSecretBytes.length, "AES");

            byte[] iv = Arrays.copyOfRange(clientSecretBytes, 0, 16);
            IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);

            String algorithm = "AES/CBC/PKCS5Padding";

            try {
                String mobile = decrypt(algorithm, encrypt_mobile, secretKey, ivParameterSpec);
                jsonObject.put("phone", mobile);
            } catch (Exception e) {
                log.info("手机号解密失败");
                e.printStackTrace();
            }
        }

        return jsonObject;
    }

    /**
     *  解密手机号
     */
    public static String decrypt(String algorithm, String cipherText, SecretKey key, IvParameterSpec iv)
            throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException {

        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, key, iv);
        byte[] plainText = cipher.doFinal(Base64.getDecoder().decode(cipherText));
        return new String(plainText);
    }

    /**
     *  视频列表
     * @return
     */
    public static VideoDataDTO videoList(String open_id, String access_token, Long cursor) {


        String requestUrl = "https://open.douyin.com/video/list/" +
                "?open_id=" + open_id +
                "&access_token=" + access_token +
                "&cursor=" + cursor +
                "&count=" + 20;

        log.info("请求地址 ： {}  ", requestUrl);

        ResponseEntity<String> responseEntity = restTemplate.getForEntity(requestUrl, String.class);
        return  getResult(VideoDataDTO.class, responseEntity.getBody(), "获取视频基础数据(视频列表)");
    }


    /**
     *  视频播放分析
     * @return
     */
    public static JSONObject videoPlayData(String open_id, String access_token) {

        String requestUrl = "https://open.douyin.com/data/external/item/play/" +
                "?open_id=" + open_id +
                "&access_token=" + access_token +
                "&date_type=" + 30;

        log.info("请求地址 ： {}  ", requestUrl);

        ResponseEntity<String> responseEntity = restTemplate.getForEntity(requestUrl, String.class);
        return  getResult(responseEntity.getBody(), "获取视频播放分析");
    }


    /**
     *  粉丝信息
     * @return
     */
    public static JSONObject fansData(String open_id, String access_token) {



        String requestUrl = "https://open.douyin.com/fans/data/" +
                "?open_id=" + open_id +
                "&access_token=" + access_token;


        ResponseEntity<String> responseEntity = restTemplate.getForEntity(requestUrl, String.class);
        return  getResult(responseEntity.getBody(), "获取用户粉丝数据");
    }


    /**
     *  粉丝来源
     * @return
     */
    public static JSONObject fansSource(String open_id, String access_token) {



        String requestUrl = "https://open.douyin.com/data/extern/fans/source/" +
                "?open_id=" + open_id +
                "&access_token=" + access_token;

        log.info("请求地址 ： {}  ", requestUrl);


        ResponseEntity<String> responseEntity = restTemplate.getForEntity(requestUrl, String.class);
        return  getResult(responseEntity.getBody(), "获取用户粉丝来源");
    }

    private static JSONObject getResult(String result, String name) {
        log.info("接口 {} 返回结果：{}", name, result);
        try {
            JSONObject jsonObject = JSON.parseObject(result);
            return  jsonObject.getJSONObject("data");
        } catch (Exception e){
            e.printStackTrace();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("result", result);
            return jsonObject;
        }
    }

    private static <T> T getResult(Class<T> clazz, String result, String name) {
        log.info("接口 {} 返回结果：{}", name, result);
        try {
            JSONObject jsonObject = JSON.parseObject(result);
            return  jsonObject.getObject("data", clazz);
        } catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }




    public static void main(String[] args) {


//        JSONObject jsonObject = loginByCode("52b7c6ba2aedef6eMXIrInYhScXRHnkS3TeJ");


        JSONObject jsonObject = getUserInfo("28cc6132-69d5-4c9b-bf3e-6fc9f8b22b11", "act.889eba70b81adf3d25b83f8cf5b35400O6aP1VpYUlwFy7nISu6k9hoEkEOS");
//        JSONObject jsonObject = videoList("9423b16d-7c40-4490-adce-8357c15fc89e", "act.1079507711a8501309b5d5d1c9f88faa65YIHuHlrjHTp6KlfY0X1vaxdoBg", 0);
//        JSONObject jsonObject = videoPlayData("bd0f2251-f992-466d-b43d-7f4aef2e83a2", "act.f3d05961dece1826b46b54c3173ad303vXXGjD96ttpCdOJ30MgQymGJvdaZ");
        System.out.println(jsonObject);
    }



}
